package pers.sen.health.security;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import pers.sen.health.po.Permission;
import pers.sen.health.service.UserService;
import pers.sen.health.vo.RoleVO;
import pers.sen.health.vo.UserVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Jason
 * @version 1.0.0
 * @date 2020/11/13 21:55
 * @Description TODO
 */
//  数据库版认证对象实例   由配置类 SecurityConfig 加载此对象
@Component
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据账号 从数据库 查询 用户所有权限信息（用户名、密码、角色关键字、权限关键字）封装到UserDetails对象中
        // 将查询用户权限信息存储到userVO中
        UserVO userVO =  userService.findUserInfoByUsername(username);
        if(userVO==null){
            // 查询到结果
            return null;
        }
        // 取出角色信息
        Set<RoleVO> roles = userVO.getRoles();
        // 存放角色和权限的关键字的容器List<GrantedAuthority>
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (RoleVO role : roles) {
            // 当前用户所有角色关键字 封装到 集合中
            authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
            // 获取当前用户权限关键字
            Set<Permission> permissions = role.getPermissionSet();
            for (Permission permission : permissions) {
                // 当前用户的所有权限关键字存放到集合中
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        System.out.println("authorities = " + authorities);
        String password = userVO.getPassword();
        // 将用户名、查询到的密码和当前用户的关键字集合存放到UserDetails中（security的）
        return new User(username,password,authorities);
    }
}
